home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2249 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.1 KB

  1. Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
  2. From: Dan Pop <danpop@mail.cern.ch>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: Sat, 20 Jan 1996 01:43:12 +0100
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <9601200043.AA10246@dxmint.cern.ch>
  8. References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dorr8$i58@cloner3.netcom.com>
  9. X-NNTP-Posting-Host: hpl3sn03.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11. X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
  12.  
  13. a1s@ix.netcom.com (Andrew Snyder) writes:
  14.  
  15. >no tricks
  16. >
  17. >#define ISPOW2(x) (((x) & 1) ^ 1)
  18.  
  19. Unless I'm missing something obvious, this macro returns 1 whenever x
  20. is even. 
  21.  
  22. A solution which actually works is:
  23.  
  24. #define ISPOW2(x) (!((x) & (x) - 1))
  25.  
  26. Its only bug is that ISPOW2(0) == 1.  If this is a problem, the fix is:
  27.  
  28. #define ISPOW2(x) ((x) && (!((x) & (x) - 1)))
  29.  
  30. For best results, x should be unsigned (and with no side effects :-)
  31.  
  32. Dan
  33. -- 
  34. Dan Pop
  35. CERN, CN Division
  36. Email: danpop@mail.cern.ch 
  37. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  38.